/**
 * 拷贝多一份数组
 * @param {number[]} nums
 * @return {number[]}
 */
var nextGreaterElements = function (nums) {
    nums = nums.concat(nums);
    let res = new Array(nums.length).fill(-1),
        numsStack = [];

    for (let i = 0; i < nums.length; i++) {
        while (numsStack.length > 0 && nums[i] > nums[numsStack[numsStack.length - 1]]) {
            let topIndex = numsStack.pop()
            res[topIndex] = nums[i]
        }

        numsStack.push(i)
    }

    return res.slice(0, nums.length / 2)
};

/**
 * 节省空间时间版
 * @param {number[]} nums
 * @return {number[]}
 */
var nextGreaterElements = function (nums) {
    let numsLen = nums.length,
        res = new Array(numsLen).fill(-1),
        numsStack = [];

    for (let i = 0; i < numsLen * 2 - 1; i++) {
        while (numsStack.length > 0 && nums[i % numsLen] > nums[numsStack[numsStack.length - 1]]) {
            let topIndex = numsStack.pop()
            res[topIndex] = nums[i % numsLen]
        }

        numsStack.push(i % numsLen)
    }

    return res
};
